package com.ayi.dao.cartdao;

import com.ayi.bean.Book;
import com.ayi.utils.CloseConn;
import com.ayi.utils.GetConn;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author Ayingzz
 * @create 2021/11/28 14:28
 */
public class AddCart {

    /**
     * 添加一个购物车
     * @param username
     * @return
     */
    public boolean addCart(String username) {
        Connection conn = new GetConn().getConnection();
        String sql = "insert into Carts value(?, '')";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.execute();
            return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 往购物车里加书
     * @param username
     * @param book
     * @return
     */
    public boolean addBookIntoCartByUsername(String username, Book book) {
        Connection conn = new GetConn().getConnection();
        StringBuilder sb = new QueryCart().queryCartWithCreateAStringBuilderByUsername(username);
        String sql = "update Carts set cartlist = ? where username = ?";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, sb.append(book.toStringCartBuild()).toString());
            ps.setString(2, username);
            ps.execute();
            return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
}
